<?php

/**
 * MySQL dump tool written in PHP
 * Copyright (C) 2008 by Mantas Zimnickas <sirexas@gmail.com>
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License.
 * 
 * For more information see the file gpl.txt or go to
 * http://www.gnu.org/copyleft/gpl.html
 */


// File where database backup shoul be stored.
define('DBDUMP_FILENAME', dirname(__FILE__).'/dbdump-'.date('Ymd').'.sql');

// Database connection parameters.
//define('DBDUMP_DSN', 'mysql:dbname=test;host=localhost');
define('DBDUMP_DSN', 'mysql:dbname=test;host=localhost');
define('DBDUMP_USERNAME', 'username');
define('DBDUMP_PASWORD', '');



/**
 * Main function, that actualy creates database dump.
 */
function buildDatabaseDump($fp, $dsn, $username, $password) {
    $dsn = pdo_parse_dsn($dsn);
    $link = mysql_connect($dsn['host'], $username, $password);
    if ($link) {
        $db_selected = mysql_select_db($dsn['dbname'], $link);
    }
    if (!$link || !$db_selected) {
        trigger_error('Con\'t connect to database.');
        return;
    }

    $tblrs = mysql_query("SHOW TABLES");

    while (list($table) = mysql_fetch_row($tblrs)) {

        fwrite($fp, "DROP TABLE IF EXISTS `$table`;\n");
        list(, $create_statement) = mysql_fetch_row(mysql_query("SHOW CREATE TABLE `$table`"));
        fwrite($fp, $create_statement.";\n");

        list($cnt) = mysql_fetch_row(mysql_query("SELECT COUNT(*) FROM `$table`"));
        if ($cnt > 0) {
            fwrite($fp, "LOCK TABLES `$table` WRITE;\n");
            fwrite($fp, "/*!40000 ALTER TABLE `$table` DISABLE KEYS */;\n");
            fwrite($fp, "INSERT INTO `$table` VALUES ");

            $rs = mysql_query("SELECT * FROM `$table`");
            for ($i=0; $values = mysql_fetch_row($rs); $i++) {
                fwrite($fp, ($i?',':'') .'('.buildInsertValues($link, $values).')');
            }
            fwrite($fp, ";\n");

            fwrite($fp, "/*!40000 ALTER TABLE `$table` ENABLE KEYS */;\n");
            fwrite($fp, "UNLOCK TABLES;\n");
        }
        fwrite($fp, "\n\n");
    }

}

/**
 * Helper function, that creates string of one row values for INSERT statment.
 */
function buildInsertValues($link, $values) {
    $ret = array();
    $cnt = sizeof($values);
    for ($i=0; $i<$cnt; $i++) {
        $ret[] = "'".mysql_real_escape_string($values[$i])."'";
    }
    return implode(', ', $ret);
}


/**
 * Parses PDO dsn
 */
function pdo_parse_dsn($dsn) {
    list(, $dsn) = explode(':', $dsn, 2);
    $ret = array();
    foreach (explode(';', $dsn) as $param) {
        list($name, $value) = explode('=', $param, 2);
        $ret[$name] = $value;
    }
    return $ret;
}



/**
 * This function demonstrates how to use functions described above.
 * Also if this script is called directly, then this function will be called.
 */
function main() {
    $fp = fopen(DBDUMP_FILENAME, 'w');
    if ($fp) {
        buildDatabaseDump($fp, DBDUMP_DSN, DBDUMP_USERNAME, DBDUMP_PASWORD);
        fclose($fp);
        chmod(DBDUMP_FILENAME, 0666);
    }
    else {
        trigger_error('Can\'t open file for storing database dump.', E_USER_ERROR);
    }
}


// If this file is executed directly, run dump functions.
if (__FILE__ == $_SERVER['SCRIPT_FILENAME']) {
    main();
}



